<template>
  <u-popup :show="show" :round="20" mode="bottom" @close="close">
    <view class="payment-popup">
      <view class="popup-head">
        <view class="title">确认支付</view>
        <view v-if="source == 'integral'" class="price"
          >{{ integral }}积分+￥{{ price + ".00" }}</view
        >
        <view v-else class="price">￥{{ price + ".00" }}</view>
      </view>
      <template v-if="isCountDown">
        <u-count-down
          ref="countDown"
          :time="30 * 60 * 1000"
          format="HH:mm:ss"
          :autoStart="false"
          @change="countDownChange"
        >
          <view class="tooltip">
            请在
            <span>{{ timeData.minutes }}分</span>
            <span>{{ timeData.seconds }}秒</span>
            内支付，过时将被取消
          </view>
        </u-count-down>
      </template>
      <template v-if="payType == 1">
        <view class="password-box">
          <u-code-input
            v-model="password"
            dot
            size="48"
            @finish="codeInputFinish"
          ></u-code-input>
        </view>
        <view class="forget" @click="pageTo('/subPages/mine/administrator')">{{
          payPassword == 1 ? "设置密码" : "忘记密码"
        }}</view>
      </template>
      <view class="pay-type">
        <view
          class="pay-type-item"
          v-for="(item, index) in payment"
          :key="index"
          @click="checkPayType(item.id)"
        >
          <view class="left">
            <image :src="item.img"></image>
            <view>{{ item.name }}</view>
          </view>
          <image
            v-if="item.id == payType"
            class="right"
            src="../../static/images/detail/activechoose.png"
            mode=""
          ></image>
          <image
            v-else
            class="right"
            src="../../static/images/detail/circle.png"
            mode=""
          ></image>
        </view>
      </view>
      <view class="popup-bottom">
        <button type="default" @click="submit" :plain="true">立即支付</button>
      </view>
      <u-modal
        confirmColor="#ff5566"
        showCancelButton="true"
        title="确认取消支付吗？"
        :show="modalShow"
        ref="uModal"
        :asyncClose="true"
        @cancel="payCancel"
        @confirm="payConfirm"
      >
        超时支付失效后，订单会被取消哦
      </u-modal>
    </view>
  </u-popup>
</template>

<script>
import userApi from "@/api/user";
import { formatBigNumber } from "@/utils/index";

export default {
  name: "PaymentPopup",
  emits: ["close", "submit"],
  props: {
    // 是否展示弹出层
    show: {
      type: Boolean,
      default: false,
    },
    // 支付金额
    price: {
      type: Number | String,
      default: 0,
    },
    // 商品所需积分
    integral: {
      type: Number | String,
      default: 0,
    },
    // 来源 order-订单列表 cart-购物车 detail-商品详情 cloud-云库存补货 integral-积分商城
    source: {
      type: String,
      default: "order",
    },
    isCountDown: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      timeData: {}, // 倒计时
      password: "", // 密码
      payType: 1, // 支付方式 1-余额支付
      modalShow: false, // 是否展示模态框
      payPassword: 1, // 1-设置密码 2-忘记密码（修改密码）
      payment: [
        {
          id: 1,
          img: "../../static/images/confirmOrder/yve.png",
          name: "余额支付（余额0）",
        },
        {
          id: 2,
          img: "../../static/images/confirmOrder/weixin.png",
          name: "银联支付",
        },
      ],
    };
  },
  created() {},
  mounted() {
    this.payPassword = uni.getStorageSync("userInfo").payPassword;
    this.getUserInfo();
    // 防止组件因条件渲染 start方法报错
    if (
      this.isCountDown &&
      this.$refs.countDown &&
      typeof this.$refs.countDown.start === "function"
    ) {
      setTimeout(() => {
        this.$refs.countDown.start();
      }, 1000);
    }
  },
  methods: {
    // 获取用户余额
    getUserInfo() {
      userApi.fetchUserInfo().then((res) => {
        if (res.code == 200) {
          if (this.source == "integral") {
            this.payment[0].name = `余额和积分支付 (余额:${
              formatBigNumber(res.user.remainingSum) || 0
            } 积分:${formatBigNumber(res.user.creditScore) || 0})`;
          } else {
            this.payment[0].name = `余额支付 (余额${
              formatBigNumber(res.user.remainingSum) || 0
            })`;
          }
        }
      });
    },
    countDownChange(e) {
      this.timeData = e;
    },
    checkPayType(id) {
      if (this.payType == id) return;
      this.payType = id;
    },
    codeInputFinish() {
      // console.log("输入完毕");
      uni.hideKeyboard();
    },
    pageTo(url) {
      uni.navigateTo({
        url,
      });
    },
    payCancel() {
      this.modalShow = false;
    },
    payConfirm() {
      this.modalShow = false;
      this.$emit("close");
    },
    close() {
      if (this.source == "cloud") {
        this.$emit("close");
      } else {
        this.modalShow = true;
      }
    },
    submit() {
      if (this.payType == 1) {
        // 余额支付
        if (this.password == "") {
          uni.showToast({
            title: "请输入支付密码",
            icon: "none",
          });
          return;
        }
        this.$emit("submit", {
          payCode: this.password,
          payType: this.payType,
        });
      }
      if (this.payType == 2) {
        // 第三方平台支付
        console.log("this.price-----", this.price);
        uni.openEmbeddedMiniProgram({
          appId: "wx16c11bc34e06caa5",
          extraData: {
            apikey: "00014005",
            money: 0.01,
            mch_orderid: 2023464664565,
            remarks: "测试小程序跳转支付",
          },
          envVersion: "release", // develop（开发版），trial（体验版），release（正式版）
          path: "pages/index/onlinepay?type=embed",
          success(res) {
            console.log("res-----", res);
          },
        });
      }
    },
  },
};
</script>

<style lang="less" scoped>
button {
  margin: 0;
  padding: 0;
  border: none;
}

button::after {
  border: none;
}

.payment-popup {
  position: relative;
  width: 100%;
  height: 60vh;
  padding: 20rpx 28rpx;

  .popup-head {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20rpx 0 0;
    color: #000;

    .title {
      text-align: center;
      font-size: 32rpx;
    }

    .price {
      font-size: 52rpx;
      font-weight: 600;
    }
  }

  .tooltip {
    padding: 0 0 32rpx;
    border-bottom: 1px solid #dddddd;
    text-align: center;
    font-size: 26rpx;

    span {
      color: #ff4254;
    }
  }

  .password-box {
    display: flex;
    justify-content: center;
    padding: 32rpx 0;
  }

  .forget {
    width: 676rpx;
    margin: 8rpx auto 0;
    color: #409eff;
    font-size: 24rpx;
  }

  .pay-type {
    padding: 16rpx 10rpx;

    .pay-type-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 80rpx;

      .left {
        display: flex;

        image {
          width: 40rpx;
          height: 40rpx;
          margin: 0 8rpx 0 0;
        }
      }

      .right {
        width: 40rpx;
        height: 40rpx;
      }
    }
  }

  .popup-bottom {
    position: absolute;
    bottom: 0;
    left: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 150rpx;
    border-top: 1px solid #dddddd;

    button {
      width: 80%;
      background-color: #000;
      color: #fff;
      border-radius: 50rpx;
    }
  }
}
</style>
